package best.driver.android.manager;

import android.text.TextUtils;
import android.util.Config;
import android.widget.ListView;
import android.widget.TextView;
import best.driver.android.Activity.Order.OrderOperationActivity;
import best.driver.android.AppInfo;
import best.driver.android.Beans.*;
import best.driver.android.BestApp;
import best.driver.android.BuildConfig;
import best.driver.android.Event.NewPositionEvent;
import best.driver.android.Event.OrderFeeEvent;
import best.driver.android.Map.location.BestLocationHelper;
import best.driver.android.Model.OrderDetailModel;
import best.driver.android.RequestFactory;
import best.driver.android.Utils.Logger;
import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.ApiArrayRequest;
import best.driver.android.common.network.ApiObjectRequest;
import best.driver.android.common.network.ApiRequest;
import best.driver.android.common.network.BestError;
import com.activeandroid.query.Select;
import de.greenrobot.event.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiangxuefeng on 15/8/18.
 */
public class OrderManager {

    private static class OrderManagerHolder {
        private static final OrderManager instance = new OrderManager();
    }

    public static OrderManager getInstance() {
        return OrderManagerHolder.instance;
    }

    private OrderDetailInfo mCurrentOrder;

    public OrderDetailInfo getCurrentOrder() {
        return mCurrentOrder;
    }

    public void setCurrentOrder(OrderDetailInfo orderDetailInfo) {
        this.mCurrentOrder = orderDetailInfo;
    }

    public void setPrice(double price) {
        mCurrentOrder.actualPrice = price;
    }

    public double getPrice() {
        return mCurrentOrder.actualPrice;
    }

    private List<OrderListInfo.Records> mCurrentOrders;

    public void setCurrentOrders(List<OrderListInfo.Records> orders) {
        mCurrentOrders = orders;
        boolean hasCurrent = false;
        if(orders != null && orders.size() > 0) {
            for(int i = 0; i < orders.size(); i++) {
                OrderListInfo.Records record = orders.get(i);
                if (isInProcessing(record.status)) {
                    hasCurrent = true;
                    if(mCurrentOrder != null && record.orderId.equals(mCurrentOrder.orderId)) {
                        mCurrentOrder.status = record.status;
                    } else {
                        mCurrentOrder = new OrderDetailInfo();
                        mCurrentOrder.orderId = record.orderId;
                        mCurrentOrder.status = record.status;
                    }
                }
            }
        }
        if(!hasCurrent) {
            mCurrentOrder = null;
        }
    }

    private boolean isInProcessing(String status) {
        if(TextUtils.isEmpty(status)) {
            return false;
        } else if (status.equals(OrderStatus.STARTED) || status.equals(OrderStatus.LOADING) || status.equals(OrderStatus.IN_TRANSIT)
                || status.equals(OrderStatus.UNLOADING)) {
            return true;
        }
        return false;
    }

    public List<OrderListInfo.Records> getCurrentOrders() {
        if(mCurrentOrders == null) {
            return new ArrayList<OrderListInfo.Records>();
        }
        return mCurrentOrders;
    }

    public void refreshCurrentOrders() {
        ApiObjectRequest<OrderListInfo> request = RequestFactory.createGetOrderListInfo("0", "50", true);
        request.setListener(new ApiRequest.ApiRequestListener<OrderListInfo>()
                            {
                                @Override
                                public void onRequestSuccess(OrderListInfo response) {
                                    if (response != null) {
                                        mCurrentOrders = response.records;
                                    }
                                }

                                @Override
                                public void onRequestError(BestError error) {

                                }
                            }
        );
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    public void updateCurrentOrderModel(double lng, double lat) {
        if(mCurrentOrder != null) {
            List<OrderDetailModel> models = new Select().from(OrderDetailModel.class).where("orderId = ?", mCurrentOrder.orderId).execute();
            if(models != null && models.size() > 0) {
                OrderDetailModel model = models.get(0);
                if(!BestLocationHelper.isSameLocation(lng, lat, model.lastLng, model.lastLat)) {
                    if(OrderStatus.IN_TRANSIT.equals(mCurrentOrder.status)) {
                        if(lng > 1e-6 && lat > 1e-6 && model.lastLng > 1e-6 && model.lastLat > 1e-6) {
                            double subDistance = BestLocationHelper.getLongDistance(lng, lat, model.lastLng, model.lastLat);
                            long subTime = System.currentTimeMillis() - model.lastLocationTime;
                            if(subTime > 0) {
                                double speed = subDistance / (subTime / 1000);
                                if(speed > 40) {
                                    return;
                                }
                            }
                            if(BuildConfig.DEBUG) {
                                AppInfo.showToast(BestApp.getInstance().getApplicationContext(), "上一点到该点距离: " + subDistance + "米");
                            }
                            model.distance += subDistance;
                        }
                    }
                    model.lastLng = lng;
                    model.lastLat = lat;
                    if(model.startLat < 1 || model.startLng < 1) {
                        model.startLat = lat;
                        model.startLng = lng;
                    }
                    model.lastLocationTime = System.currentTimeMillis();
                    model.save();
                    EventBus.getDefault().post(model);
//                    if(model.startTime > 0 && model.endTime < model.startTime) {
//                        //getOrderPrice(model.orderId, model.distance * 20, (System.currentTimeMillis() - model.startTime) / 1000 * 30);
//                        if(OrderStatus.LOADING.equals(mCurrentOrder.status) || OrderStatus.UNLOADING.equals(mCurrentOrder.status)) {
//                            EventBus.getDefault().post(new NewPositionEvent(model.orderId, model.distance,
//                                    model.waitTime + System.currentTimeMillis() - model.startTime));
//                        } else {
//                            EventBus.getDefault().post(new NewPositionEvent(model.orderId, model.distance, model.waitTime));
//                        }
//                    }
                    if(!(BestApp.getInstance().getLastActivity() instanceof OrderOperationActivity)) {
                        if(model == null) {
                            return;
                        }
                        if(!model.orderId.equals(mCurrentOrder.orderId)) {
                            return;
                        }
                        long waitTime = 0;
                        if(OrderStatus.LOADING.equals(mCurrentOrder.status) || OrderStatus.UNLOADING.equals(mCurrentOrder.status)) {
                            waitTime = (System.currentTimeMillis() - model.startTime + model.waitTime) / 1000;
                        } else {
                            waitTime = model.waitTime / 1000;
                        }
                        getOrderPrice(mCurrentOrder.orderId, model.distance, waitTime);
                    }

                    Logger.d("LocationSameFalse", lng + " " + lat);
                }
                Logger.d("LocationSameTrue", lng + " "+lat);

            }
        }
    }

    public void deleteCurrentOrder(String orderId) {
        if(!TextUtils.isEmpty(orderId) && mCurrentOrder != null && orderId.equals(mCurrentOrder.orderId)) {
            mCurrentOrder = null;
        }
    }

    public void deleteCurrentOrder() {
        mCurrentOrder = null;
    }

    public void getOrderPrice(String orderId, final double distance, long waitTime) {
         ApiObjectRequest<OrderFeeInfo> request = RequestFactory.createGetOrderFeeRequest(orderId, (int) distance, waitTime);
        request.setListener(new ApiRequest.ApiRequestListener<OrderFeeInfo>() {
            @Override
            public void onRequestSuccess(OrderFeeInfo response) {

            }

            @Override
            public void onRequestError(BestError error) {

            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    public boolean isProcessing(String status) {
        if(OrderStatus.WAIT_START.equals(status) || OrderStatus.LOADING.equals(status) || OrderStatus.STARTED.equals(status) ||
                OrderStatus.IN_TRANSIT.equals(status) || OrderStatus.UNLOADING.equals(status)) {
            return true;
        }
        return false;
    }

    public boolean canSavePosition(String status) {
        if(OrderStatus.IN_TRANSIT.equals(status)) {
            return true;
        }
        return false;
    }
}
